package com.etoak.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.redis.service.RedisService;
import com.etoak.vo.CodeVO;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/code")
public class CodeController {
    @Autowired
    RedisService redisService;
    @Autowired
    DefaultKaptcha defaultKaptcha;
    //获得验证码
    @GetMapping("/getCode")
    public ResultVO<CodeVO> getCode() throws IOException {
        //验证码后半段放入redis中
        String text = defaultKaptcha.createText();
        //1+1=?@2
        String[] strings = text.split(StrUtil.AT);

        String uuid = IdUtil.simpleUUID();
        //redis的key是code:uuid
        String codeKey = CommonConstant.CODE_KEY_PREFIX+uuid;
        redisService.setex(codeKey,strings[1],5, TimeUnit.MINUTES);

        //图片-->字节数组-->base64
        BufferedImage image = defaultKaptcha.createImage(strings[0]);
        FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
        ImageIO.write(image,"png",outputStream);

        String baseCode = Base64.encode(outputStream.toByteArray());
        //codeUrl是base64编码的验证码图片
        String codeUrl = "data:image/png;base64,"+baseCode;
        CodeVO codeVO=new CodeVO(uuid,codeUrl);
        return ResultVO.success(codeVO);

    }
}
